package base.cglib;

import com.itheima.service.impl.UserServiceImpl;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.awt.*;
import java.lang.reflect.Method;

public class UserServiceCglibProxy {
    public static UserServiceImpl createUserServiceCglibProxy(Class clazz){
        // 创建Enhance对象（可以理解为内存中动态创建了一个类的字节码）
        Enhancer enhancer = new Enhancer();
        // 设置Enchance对象的父类是指定类型UserServiceImpl
        enhancer.setSuperclass(clazz);
        Callback callback = new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object ret = methodProxy.invokeSuper(o, objects);
                if (method.getName().equals("save")){
                    System.out.println("刮大白");
                }
                return ret;
            }
        };
        // 设置回调方法
        enhancer.setCallback(callback);
        // 使用Enchancer对象创建对应对象
        return (UserServiceImpl) enhancer.create();

    }

}
